package template.web;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分页工具
 * 封装了页面记录数，排序方式，数据集
 * 
 * 这个对象一般放在handler方法参数里头，配合使用OrderTypeFormatter，Spring MVC可以正确构造该对象
 * 
 * @author mengyang
 * 
 */
public class Page<T> {
	
	public static final int DEFAULT_CURRENT_PAGE = 0;	//默认当前页
	public static final int DEFAULT_PAGE_SIZE = 10;		//默认每页记录数
	
	/**
	 * 排序方式
	 */
	public enum OrderType{
		ASC, DESC
	}
	
	private int currentPage = DEFAULT_CURRENT_PAGE;  	//当前页码，从0开始
	private int pageSize = DEFAULT_PAGE_SIZE;     		//每页记录数
	
	private int totalCount;    							//总记录数
	
	/**
	 * 页面排序方式，格式：OrderType_OrderBy，例如：desc_id
	 * 多个可以用,隔开，例如：desc_id,asc_time
	 */
	private String orderBy;			
	
	private Map<String, OrderType> orderMap = new HashMap<String, OrderType>();  //页面排序
	
	private List<T> dataList = Collections.emptyList();  	//页面记录集
	
	public Page(){
		
	}
	
	public Page(int currentPage, int pageSize){
		this.currentPage = currentPage;
		this.pageSize = pageSize;
	}
	
	public Page(int currentPage, int pageSize, Map<String, OrderType> orderMap){
		this.currentPage = currentPage;
		this.pageSize = pageSize;
		this.orderMap = orderMap;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public Page<T> setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
		return this;
	}

	public int getTotalCount() {
		return totalCount;
	} 

	public Page<T> setTotalCount(int totalCount) {
		this.totalCount = totalCount;
		return this;
	}

	public int getPageSize() {
		return pageSize;
	}

	public Page<T> setPageSize(int pageSize) {
		this.pageSize = pageSize;
		return this;
	}

	public List<T> getDataList() {
		return dataList;
	}

	public Page<T> setDataList(List<T> dataList) {
		this.dataList = dataList;
		return this;
	}
	
	public Map<String, OrderType> getOrderMap() {
		return orderMap;
	}

	public Page<T> setOrderMap(Map<String, OrderType> orderMap) {
		this.orderMap = orderMap;
		return this;
	}
	
	public String getOrderBy() {
		return orderBy;
	}

	public Page<T> setOrderBy(String orderBy) {
		String[] orderArray = orderBy.split(",");
		for(String orderStr : orderArray){
			String[] orders = orderStr.split("_");
			if("asc".equals(orders[0].toLowerCase().trim())){
				addOrder(orders[1], OrderType.ASC);
			}else if("desc".equals(orders[0].toLowerCase().trim())){
				addOrder(orders[1], OrderType.DESC);
			}else{
				throw new IllegalArgumentException("orderBy字段格式错误: " + orderBy);
			}
		}
		
		this.orderBy = orderBy;
		
		return this;
	}

	/**
	 * 添加排序方式
	 * @param order 排序方式
	 * @param orderBy 根据哪个字段排序
	 */
	public Page<T> addOrder(String orderBy, OrderType orderType){
		this.orderMap.put(orderBy, orderType);
		return this;
	}

}
